package ctrl

import (
	"chat-im/model"
	"chat-im/service"
	"chat-im/util"
	"net/http"
)

// 登录
func UserLogin(writer http.ResponseWriter,
	request *http.Request) {
	//解析参数
	request.ParseForm()
	mobile := request.PostForm.Get("mobile")
	passwd := request.PostForm.Get("passwd")
	user, err := userService.Login(mobile, passwd)
	if err != nil {
		util.RespFail(writer, err.Error())
	} else {
		util.RespOk(writer, user, "")
	}
}

var userService service.UserService

// 注册
func UserRegister(writer http.ResponseWriter,
	request *http.Request) {
	// request.ParseForm()
	// mobile := request.PostForm.Get("mobile")
	// plainpwd := request.PostForm.Get("passwd")
	// nickname := fmt.Sprintf("user%06d", rand.Int31())
	// avatar := ""
	// sex := model.SEX_UNKNOWN
	// user, err := userService.Register(mobile, plainpwd, nickname, avatar, sex)

	//有了数据绑定方法,不需要其他的啦
	var user model.User
	util.Bind(request, &user)
	user, err := userService.Register(user.Mobile, user.Passwd, user.Nickname, user.Avatar, user.Sex)
	if err != nil {
		util.RespFail(writer, err.Error())
	} else {
		util.RespOk(writer, user, "")
	}
}

// 获取用户信息
func UserFind(writer http.ResponseWriter,
	request *http.Request) {
	//request.ParseForm()
	//id := request.PostForm.Get("id")
	//userId, _ := strconv.ParseInt(id, 10, 64)
	//user := userService.Find(userId)

	var user model.User
	util.Bind(request, &user)
	user = userService.Find(user.Id)
	if user.Id == 0 {
		util.RespFail(writer, "该用户不存在")
	} else {
		util.RespOk(writer, user, "")
	}
}
